----------------------------------------------------------------------------------
-- Company:        N/A
-- Engineer:       Brian Wiec
-- Create Date:    17:04:18 12/14/2012 
-- Design Name:    spi2led
-- Module Name:    spi2led - Behavioral 
-- Project Name:   MARK-1
-- Target Devices: xc6slx9-3TQG144
-- Tool versions:  ISE 14.3
-- Description:    This design takes commands from a SPI master (i.e. Raspberry
--						 Pi, Beagle Bone, Arduino, etc.) and toggles the MARK-1 on-board
--						 user LEDs.
-- Dependencies: 
--						 - spi_slave.vhd
--						 - spi2led.ucf
-- Revision: 
--						 - Revision 1.00 - 14 December 2012 - Verification on board at
--																		  25MHz SPI line rate
-- 					 - Revision 0.01 - 14 December 2012 - File Created
-- Additional Comments:
--						 - Note that the main clock runs at twice the rate of the SPI
--							sck rate. This is recommended by the author of the spi_slave
--							module.
--						 - Heartbeat used on LED 7 is there to indicate that the FPGA
--							has been properly configured.
-- To Do:
--						 - Insert chipscope and see how fast you can run SPI sck.
----------------------------------------------------------------------------------
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity spi2led is
	generic
	(   
		N 			: positive  := 8;   -- 8bit serial word length is default
		CPOL 		: std_logic := '0'; -- SPI mode selection (mode 0 default)
		CPHA 		: std_logic := '0'; -- CPOL = clock polarity, CPHA = clock phase.
		PREFETCH : positive  := 3    -- prefetch lookahead cycles
	);
	port
	(
		clk		: in  std_logic; -- 50 MHz
		spi_sck  : in  std_logic; -- 25 MHz
		spi_ss   : in  std_logic;
		spi_mosi : in  std_logic;
		spi_miso : out std_logic;		
		leds		: out std_logic_vector(7 downto 0)
	);
end spi2led;

architecture Behavioral of spi2led is

	signal do : std_logic_vector(N-1 downto 0);
	signal cnt : unsigned (24 downto 0);

begin

	----- Heartbeat -----
	heartbeat : process (clk)
	begin
		if rising_edge(clk) then
			if (cnt < 2**(25-1)) then
				leds(7) <= '0';
			else
				leds(7) <= '1'; -- Flash LED 7 to indicate successufl FPGA configuration
			end if;
			cnt <= cnt + 1;
		end if;
	end process;
	
	leds(6 downto 0) <= do(6 downto 0); -- The rest of the LEDs correspond to bits from SPI

	----- Instantiate SPI Slave Module -----
	spi_slave_inst : entity work.spi_slave
	generic map
	(
		N 			=> N,
		CPOL 		=> CPOL,
		CPHA 		=> CPHA
	)
	port map
	(
		----- SPI Interface Signals -----
		spi_sck_i  => spi_sck,		
		spi_ssel_i => spi_ss,
		spi_mosi_i => spi_mosi,
		spi_miso_o => spi_miso,
		
		----- User Interface Signals -----
		clk_i 	  => clk,
		di_req_o   => open,
		di_i 		  => X"a5",
		wren_i 	  => spi_ss,
		do_valid_o => open,
		do_o 		  => do
	);
			
end Behavioral;

